package com.example.fbneo_crc2;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

public class HttpUtil {
    private static String USER_AGENT = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; customie8)";

    // HTTP GET request
    public static String sendGet(String url, String charset) throws Exception {
        URL realurl = new URL(url);
        HttpURLConnection con = (HttpURLConnection) realurl.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        con.setRequestProperty("User-Agent", USER_AGENT);

        // int responseCode = con.getResponseCode();
        // System.out.println("Response Code : " + responseCode);
        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
        String inputLine;
        StringBuffer result = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            result.append(inputLine);
            result.append("\r\n");
        }
        in.close();
        con.disconnect();
        return result.toString();
    }





    // 提交表单
    public static String sendPost(String url,String header,String post, String charset) throws Exception {


        OutputStream os = null;
        BufferedReader in=null;
        HttpsURLConnection con=null;


        try{

            URL realurl = new URL(url);
            con = (HttpsURLConnection) realurl.openConnection();

            // optional default is GET
            con.setRequestMethod("POST");

            for (String line: header.split("\n")){
                if(line.trim().isEmpty()){
                    continue;
                }
                con.addRequestProperty(line.replaceAll("([^:]*): (.*)","$1"),line.replaceAll("([^:]*): (.*)","$2"));

//                System.out.println(line.replaceAll("([^:]*): (.*)","$1")+"------"+line.replaceAll("([^:]*): (.*)","$2"));
            }

            // add request header
//            con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; customie8)");
//            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");



            // 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
            con.setDoOutput(true);
            // 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
            con.setDoInput(true);
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。



            // 通过连接对象获取一个输出流
            os = con.getOutputStream();

            // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
            os.write(post.getBytes(StandardCharsets.UTF_8));


            // 发送请求
            con.connect();
            int codeNum=con.getResponseCode();
            if (codeNum != 200) {
                con.disconnect();
                System.out.println("http ErrCode:"+codeNum);
                return null;
            }


            in = new BufferedReader(new InputStreamReader(con.getInputStream(), charset));
            String inputLine;
            StringBuffer result = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                result.append(inputLine);
                result.append("\r\n");
            }
            in.close();
            con.disconnect();
            return result.toString();

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }finally {
            try{
                if(in!=null){in.close();}
                if(os!=null){os.close();}
                if(con!=null){con.disconnect();}
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }



    /**
     * 下载文件到指定目录
     * @param urlStr
     * @param fileName
     * @throws Exception
     */
    public static void downloadNet(String urlStr, String fileName) throws Exception {
        HttpURLConnection conn=null;
        InputStream inStream=null;
        FileOutputStream fs=null;
        try{

            // 下载网络文件
            int bytesum = 0;
            int byteread = 0;

            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(3000);
            conn.setReadTimeout(10000);

            // add request header
            conn.setRequestProperty("User-Agent", USER_AGENT);
            inStream = conn.getInputStream();
            fs = new FileOutputStream(fileName);

            byte[] buffer = new byte[1204];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
//            System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
            }

        } finally {
            if(fs!=null){
                fs.close();
            }
            if(inStream!=null){
                inStream.close();
            }
            if(conn!=null){
                conn.disconnect();
            }

        }


    }






}